<?php

namespace core\tpl;

use Exception;
use support\View;
use think\Template;
use think\template\TagLib;

class ThinkphpTpl extends TagLib
{

    protected $tags   =  [
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'fc' => ['attr' => 'return,app', 'close' => 0,],
     
    ];

    protected function tagFc($tag, $content)
    {
        $app    = $tag['app'];
        $return = isset($tag['return']) && trim($tag['return'] != '') ?
            $tag['return'] : 'result';

        unset($tag['app']);
        unset($tag['return']);

        $params = '';
        foreach ($tag as $key => $value) {
            $flag = substr($value, 0, 1);
            if (
                !str_starts_with($value, '$') &&
                is_string($value)
                && !$this->hasBalancedParentheses($value, [')' => '('])
            ) {
                $value = "'" . $value . "'";
            }

            $params .= $key . ':' . $value . ',';
        }

        $params = rtrim($params, ',');

        return   $parseStr = '<?php $' . $return . '= fc("' . $app . '",' . $params . ');?>';


        $result = fc($app, ...$tag);
        return '<?php $' . $return . '=' . var_export($result, true) . ';?>';
    }

    /**
     * 判断是否有成对的括号
     *
     * @param string $str
     * @param array $map
     * @return boolean
     */


    private  function hasBalancedParentheses(string $str)
    {
        if (empty($str)) {
            return false;
        }
        if (strpos($str, '(') === false && strpos($str, ')') === false) {
            return false;
        }
        $str_len = strlen($str);
        $j = $z = 0;
        for ($i = 0; $i < $str_len; $i++) {
            if ($str[$i] == '(') {
                $j++;
            }
            if ($str[$i] == ')') {
                if ($j > 0) {
                    $j--;
                } else {
                    $z = 1;
                }
            }
        }
        if (empty($j) && empty($z)) {
            return true;
        }
        return false;
    }
}
